// Robert van Seggelen, robertvs@gmail.com
// 2011
jQuery.fn.YouTubePlayer = function(userOptions) {
	//Youtube API
	//http://code.google.com/intl/sv-SE/apis/youtube/js_api_reference.html
	//default options
	var options = {
		player: null,
		domElement: $(this)[0],
		videoId: 'XSV-VtJfwRw',
		playerOptions: {
			height: $(this).height(),
			width: $(this).width(),
			autoPlay: 1,
			showControls: 0,
			volume: 80
		},
		onPlayerReady: function(event){},
		onVideoEnded: function(event){},
		onVideoPlaying: function(event){},
		onVideoPaused: function(event){},
		onError: function(msg){}
	}; 
	//merge the default options with the user defined ones
	$.extend(true, options, userOptions);
	
	// First get the youtube script
	$.getScript('http://www.youtube.com/player_api', function(data, textStatus){
		//When this has loaded ot will call the onYouTubePlayerAPIReady function which we override in this method
	});
	// Hook up to the ready Event and create the player object
	window.onYouTubePlayerAPIReady = function(){
		options.player = new YT.Player(options.domElement.id, {
			height: options.playerOptions.height,
			width: options.playerOptions.width,
			videoId: options.videoId,
			playerVars: { 
				'autoplay': options.playerOptions.autoPlay, 
				'controls': options.playerOptions.showControls
			},
			events: {
				'onReady': onPlayerReady,
				'onStateChange': onPlayerStateChange,
				'onError': onPlayerError
			}
        });
	};
	//function will be called when player is ready
	function onPlayerReady(event) {
		options.onPlayerReady(event);
		this.IsReady = true;
		options.player.setVolume(options.playerOptions.volume);
    }
	//for every state change in the video this will be called 
	function onPlayerStateChange(event) {
		//alert('onPlayerStateChange');
		switch(event.data){
			case YT.PlayerState.PLAYING:
				options.onVideoPlaying(event);
				break;
			case YT.PlayerState.ENDED:
				options.onVideoEnded(event);
				break;
			case YT.PlayerState.PAUSED:
				options.onVideoPaused(event);
				break;
		}
	}
	function onPlayerError(event){
		options.onError("something went wrong, debug youtube library for error info");
		console.log(event);
	}
	//will play the current loaded video
	this.Play = function(){
		if(options.player)
			options.player.playVideo();
		else
			options.onError("Youtube Player not initialized");
	}
	//will play the submitted video id
	this.PlayVideo = function(videoId){
		if(options.player)
			options.player.loadVideoById(videoId);
		else
			options.onError("Youtube Player not initialized");
	}
	//will cue a video
	this.CueVideo = function(videoId){
		if(options.player)
			options.player.cueVideoById(videoId);
	}
	//will stop all current playback
	this.Stop = function(){
		if(options.player)
			options.player.stopVideo();
		else
			options.onError("Youtube Player not initialized");
		//alert('stop');
	}
	//will pause current playback
	this.Pause = function(){
		alert('pause not implemented. use stop');
	}
	this.PlayUrl = function(ytUrl){
		var videoId = this.GetYoutubeIdFromUrl(ytUrl);
		if(videoId)
			this.PlayVideo(videoId);
		else
			options.onError("Can't get video id from "+ytUrl);
	}
	this.GetYoutubeIdFromUrl(url){
		var ytregexp = /(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/ ]{11})/i;
		var videoId = url.match(ytregexp);
		if(videoId)
			return videoId[1];
		else
			return url;
	}
	return this;
};